package com.ycz.shiroboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description
 * @ClassName TestController
 * @Author yanchengzhi
 * @date 2021.09.25 15:10
 */
@Controller
@RequestMapping("/")
public class TestController {

    /*
    * @description: 默认跳转
    * @param: [model]
    * @return: java.lang.String
    * @author: yanchengzhi
    * @date: 2021/9/25 16:20
    */
    @RequestMapping("")
    public String toIndexPage(Model model) {
        model.addAttribute("key","Shiro安全框架");
        return "index";
    }

    /*
    * @description: 跳往添加页面
    * @param: []
    * @return: java.lang.String
    * @author: yanchengzhi
    * @date: 2021/9/25 16:21
    */
    @RequestMapping("/user/add")
    public String toAddPage() {
        return "/user/add";
    }
    
    /*
    * @description: 跳往编辑修改页面
    * @param: []
    * @return: java.lang.String
    * @author: yanchengzhi
    * @date: 2021/9/25 16:22
    */
    @RequestMapping("/user/edit")
    public String toEditPage() {
        return "/user/edit";
    }

    @RequestMapping("/toLogin")
    public String toLoginPage(){
        return "login";
    }

    /*
     * @description: 登录校验
     * @param: [username, password, model]
     * @return: java.lang.String
     * @author: yanchengzhi
     * @date: 2021/9/25 17:16
     */
    @RequestMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          Model model) {
        // 获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        // 如果当前用户未进行认证
        if(!currentUser.isAuthenticated()) {
            // 将用户名和密码加密封装为token
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            try {
                // 执行登录
                currentUser.login(token);
            } catch (UnknownAccountException uae) { // 用户名不存在
                model.addAttribute("errorMsg","用户名不存在！");
                return "login";
            } catch (IncorrectCredentialsException ice) { // 密码错误
                model.addAttribute("errorMsg", "密码错误！");
                return "login";
            }
        }
        return "index";
    }

    /*
     * @description: 没有权限的跳转
     * @param: []
     * @return: java.lang.String
     * @author: yanchengzhi
     * @date: 2021/9/25 20:27
     */
    @ResponseBody
    @RequestMapping("/noAuth")
    public String noAuth() {
        return "您没有权限访问该资源！";
    }


}
